package com.jlnk.androidfmc.fragment.fragments;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.jlnk.androidfmc.MainActivity;
import com.jlnk.androidfmc.R;
// 导入您的 Fragment 类
import com.jlnk.androidfmc.database.ProductDatabaseHelper;
import com.jlnk.androidfmc.entity.Product;
import com.jlnk.androidfmc.fragment.fragments.homefragment.FruitsVegetablesFragment;
import com.jlnk.androidfmc.fragment.fragments.homefragment.GrainsOilFragment;
import com.jlnk.androidfmc.fragment.fragments.homefragment.FarmSuppliesFragment;
import com.jlnk.androidfmc.fragment.fragments.homefragment.RecommendFragment;

import java.util.ArrayList;
import java.util.List;

public class BuyerHomeFragment extends Fragment {

    private FrameLayout fragmentContainer;
    private TextView tvRecommend, tvFruitVegetables, tvGrainOil, tvFarmingSupplies;

    private RecommendFragment recommendFragment;
    private FruitsVegetablesFragment fruitsVegetablesFragment;
    private GrainsOilFragment grainsOilFragment;
    private FarmSuppliesFragment farmSuppliesFragment;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_buyer_home, container, false);

        Button btn_search = view.findViewById(R.id.btn_search);
        if (btn_search != null) {
            btn_search.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onSearchClicked(v); // Call the onSearchClicked method
                }
            });
        } else {
            Toast.makeText(getContext(), "搜索按钮未找到", Toast.LENGTH_SHORT).show();
        }
        // 初始化 FrameLayout 容器
        fragmentContainer = view.findViewById(R.id.fragment_container);

        // 初始化 Fragment
        recommendFragment = new RecommendFragment();
        fruitsVegetablesFragment = new FruitsVegetablesFragment();
        grainsOilFragment = new GrainsOilFragment();
        farmSuppliesFragment = new FarmSuppliesFragment();

        // 初始化 TextView
        tvRecommend = view.findViewById(R.id.tv_recommend);
        tvFruitVegetables = view.findViewById(R.id.tv_fruit_vegetables);
        tvGrainOil = view.findViewById(R.id.tv_grain_oil);
        tvFarmingSupplies = view.findViewById(R.id.tv_farming_supplies);

        // 初始化时加载推荐 Fragment
        loadFragment(recommendFragment);

        // 设置点击事件
        setupClickListener(tvRecommend, recommendFragment);
        setupClickListener(tvFruitVegetables, fruitsVegetablesFragment);
        setupClickListener(tvGrainOil, grainsOilFragment);
        setupClickListener(tvFarmingSupplies, farmSuppliesFragment);

        // 设置初始状态，推荐为选中
        setupBottomLine(tvRecommend, true);

        return view;
    }

    private void setupClickListener(TextView tv, final Fragment fragment) {
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 切换 Fragment
                loadFragment(fragment);
                // 更新底部横线
                resetBottomLines();
                setupBottomLine(tv, true);
            }
        });
    }

    private void setupBottomLine(TextView tv, boolean selected) {
        if (selected) {
            tv.setBackgroundResource(R.drawable.bottom_line); // 显示横线
        } else {
            tv.setBackground(null); // 隐藏横线
        }
    }

    private void resetBottomLines() {
        setupBottomLine(tvRecommend, false);
        setupBottomLine(tvFruitVegetables, false);
        setupBottomLine(tvGrainOil, false);
        setupBottomLine(tvFarmingSupplies, false);
    }

    private void loadFragment(Fragment fragment) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.addToBackStack(null); // 添加到回退栈
        transaction.commit();
    }
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 通知MainActivity在首页显示"去卖货"按钮和图片
        MainActivity mainActivity = (MainActivity) getActivity();
        if (mainActivity != null) {
            mainActivity.setGoSellVisibility(true);
        }
    }

    public void onSearchClicked(View view) {
        // 获取 Fragment 的当前视图
        View fragmentView = getView();
        if (fragmentView != null) {
            // 隐藏“推荐”这一行
            LinearLayout linearCategories = fragmentView.findViewById(R.id.linear_categories);
            linearCategories.setVisibility(View.GONE);

            // 接下来是您的搜索逻辑...
            EditText et_searchtext = fragmentView.findViewById(R.id.et_searchtext);
            if (et_searchtext != null) {
                String searchText = et_searchtext.getText().toString();
                // 执行数据库查询...
                List<Product> products = searchDatabase(searchText);

                // 检查是否有搜索结果并展示
                if (products.isEmpty()) {
                    // 没有结果时的操作
                    showNoResultsMessage();
                } else {
                    // 有结果时的操作
                    showSearchResults(products);
                }
            } else {
                Toast.makeText(getContext(), "搜索框未找到", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getContext(), "Fragment视图未初始化", Toast.LENGTH_SHORT).show();
        }
    }


    private List<Product> searchDatabase(String searchText) {
        List<Product> results = new ArrayList<>();
        ProductDatabaseHelper dbHelper = new ProductDatabaseHelper(getContext());
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String query = "SELECT * FROM " + ProductDatabaseHelper.TABLE_PRODUCTS +
                " WHERE " + ProductDatabaseHelper.COLUMN_PRODUCT_NAME + " LIKE ?" +
                " OR " + ProductDatabaseHelper.COLUMN_PRODUCT_DESCRIPTION + " LIKE ?";
        String[] args = {"%" + searchText + "%", "%" + searchText + "%"};
        Cursor cursor = db.rawQuery(query, args);

        if (cursor.moveToFirst()) {
            do {
                Product product = new Product();
                // 从cursor中以字符串形式获取id，并设置到product对象
                String id = cursor.getString(cursor.getColumnIndex(ProductDatabaseHelper.COLUMN_PRODUCT_ID));
                product.setId(id); // 正确设置id属性

                // 获取其他字段的值并设置
                String name = cursor.getString(cursor.getColumnIndex(ProductDatabaseHelper.COLUMN_PRODUCT_NAME));
                product.setName(name);

                String description = cursor.getString(cursor.getColumnIndex(ProductDatabaseHelper.COLUMN_PRODUCT_DESCRIPTION));
                product.setDescription(description);

                String imagePath = cursor.getString(cursor.getColumnIndex(ProductDatabaseHelper.COLUMN_PRODUCT_IMAGE_PATH));
                product.setImagePath(imagePath);

                int categoryId = cursor.getInt(cursor.getColumnIndex(ProductDatabaseHelper.COLUMN_PRODUCT_CATEGORY_ID));
                product.setCategoryId(categoryId);

                double price = cursor.getDouble(cursor.getColumnIndex(ProductDatabaseHelper.COLUMN_PRODUCT_PRICE));
                product.setPrice(price);

                results.add(product);
            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return results;
    }

    private void showNoResultsMessage() {
        // 显示没有结果的消息
        // 例如，更新一个TextView的可见性
    }

    // 在 BuyerHomeFragment 或 MainActivity 中

    private void showSearchResults(List<Product> products) {
        SearchResultsFragment searchResultsFragment = SearchResultsFragment.newInstance(products);
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, searchResultsFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}